package team.hyznrj.studentsys.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mongodb.BasicDBObject;

import team.hyznrj.studentsys.dao.mapper.MBG_CourseAchievementMapper;
import team.hyznrj.studentsys.dto.StudentMessageSearchDto;
import team.hyznrj.studentsys.entity.CourseDetailEntity;
import team.hyznrj.studentsys.entity.CourseEntity;
import team.hyznrj.studentsys.entity.DBPageMessage;
import team.hyznrj.studentsys.entity.MBG_CourseAchievement;
import team.hyznrj.studentsys.entity.MBG_CourseAchievementExample;
import team.hyznrj.studentsys.entity.MBG_CourseAchievementExample.Criteria;
import team.hyznrj.studentsys.entity.PEMap;
import team.hyznrj.studentsys.entity.SimpleCourseResult;
import team.hyznrj.studentsys.exception.DataIllegalException;
import team.hyznrj.studentsys.exception.DataNullException;
import team.hyznrj.studentsys.service.CourseAchievementPlusService;
import team.hyznrj.studentsys.service.PEMapService;
import team.hyznrj.studentsys.service.StudentMessageService;
import team.hyznrj.studentsys.service.StudentMsgMapService;
import team.hyznrj.studentsys.utils.ValueUtil;

@Service
public class CourseAchievementPlusImpl implements CourseAchievementPlusService {
	@Autowired
	StudentMessageService stuService;
	@Autowired
	PEMapService peMapService;
	@Autowired
	MBG_CourseAchievementMapper mapper;
	@Autowired
	StaticDatabasesValueCache cache;
	@Autowired
	StudentMsgMapService stuMapService;
	/**
	 * MongDB主键关键字
	 */
	@Value("${StudentMessageServicePrimaryKey}")
	private String PRIMARY_KEY;
	/**
	 * 学号值
	 */
	@Value("${StudentMessageSno}")
	private String STUDENT_MESSAGE_SNO;
	/**
	 * 结果集的分页名
	 */
	private static final String RESULT_PAGE_KEY="page";
	/**
	 * 排序SQL语句
	 */
	private static final String ORDER_CAUSE_SQL = "STUDENT_ID ASC,ACADEMIC_YEAR ASC,SCHOOL_TERM ASC";
	/**
	 * 系等级
	 */
	private static final int PRO_LEVEL = 2;
	/**
	 * 模糊查询通配符
	 */
	private static final String PER_PATTERN = "%";
	/**
	 * 学生信息字段映射
	 */
	@Autowired
	private StudentMsgMapService stuMsgMapService;
	@Override
	public Object getAggregationCourse(final StudentMessageSearchDto dto) {
		Map<String, Object> result = new HashMap<>();
		if (dto != null && !StringUtils.isEmpty(dto.getFlag())) {
			dto.setOpenPage(true);
			/**
			 * 查询学生基本信息
			 */
			List<BasicDBObject> studentsSno = stuService.getStudentsSno(dto);
			
			Map<String, BasicDBObject> stuMap = new HashMap<>();
			List<String> snoList = new ArrayList<>();
			/** value->id映射 */
			Map<String, String> idMap = stuMsgMapService.getAllMsgIdMap(dto.getFlag());
			/** 将学号放入数组，方便后面进行数据库查询,另加入映射Map,为后面装载对象做准备 */
			if (studentsSno != null && studentsSno.size() > 0) {
				for (BasicDBObject obj : studentsSno) {
					String sno = obj.getString(idMap.get(STUDENT_MESSAGE_SNO));
					snoList.add(sno);
					stuMap.put(sno, obj);
				}
			}
			/** 如果需要分页，则进行分页，否则不分页 */
			if (dto.getPageIndex() != null && dto.getPageSize() != null) {
				long count = stuService.getStudentsSnoCount(dto);
				result.put(RESULT_PAGE_KEY, new DBPageMessage(dto.getPageIndex(), dto.getPageSize(), count));
			}
			/** MYSQL数据库查询 */
			MBG_CourseAchievementExample example = new MBG_CourseAchievementExample();
			Criteria criteria = example.createCriteria();
			criteria.andUserIdLike(ValueUtil.getFlag(dto.getFlag(), PRO_LEVEL) + PER_PATTERN);
			criteria.andStudentIdIn(snoList);
			/** 遍历year数组（可能存在多个year） */
			List<String> year = dto.getAcademic_year();
			List<Byte> yearVals = new ArrayList<>();
			if (year != null) {
				for (String str : year) {
					if (!StringUtils.isEmpty(str)) {
						Integer value = cache.getYearByValue(str);
						yearVals.add((byte) value.intValue());
					}
				}
				criteria.andAcademicYearIn(yearVals);
			}
			/** 按学号、学分排下序 */
			example.setOrderByClause(ORDER_CAUSE_SQL);
			/** 查询数据库，并封装对象 */
			List<MBG_CourseAchievement> selectByExample = mapper.selectByExample(example);
			List<PEMap> allPE = peMapService.getAllPE();
			List<String> peValueList = new ArrayList<>();
			for (PEMap pe : allPE) {
				peValueList.add(pe.getPeName());
			}
			/**先按学年，再按学号分*/
			Map<String,Map<String, SimpleCourseResult>> main=new HashMap<>();
			Map<String, SimpleCourseResult> data = null;
			CourseEntity courseEntity = new CourseEntity();
			for(MBG_CourseAchievement entity:selectByExample){
				Byte academicYear = entity.getAcademicYear();
				String yearStr = academicYear.toString();
				if(main.containsKey(yearStr)){
					data = main.get(yearStr);
				}else{
					data=new HashMap<>();
					main.put(yearStr, data);
				}
				String studentId = entity.getStudentId();
				SimpleCourseResult tmp=null;
				/**不存在ID则封装一下*/
				if(data.containsKey(studentId)){
					tmp = data.get(studentId);
				}else{
					tmp=new SimpleCourseResult();
					tmp.setStudentBasicMessageValue(stuMap.get(studentId), idMap);
					tmp.setYear(cache.getYearById(academicYear.intValue()));
					data.put(studentId, tmp);
				}
				if(entity.getConvertMark().doubleValue()<=60||entity.getCourseGradePoint().doubleValue()<=0){
					tmp.setGgNum(tmp.getGgNum()+1);
					tmp.setG(true);
				}
				if(peValueList.contains(entity.getCourseTitle())){
					tmp.setPeCount(tmp.getPeCount()+1);
					tmp.setPeGrade(tmp.getPeGrade()+entity.getCourseGradePoint().doubleValue());
				}else{
					String curriculumNatureValueById = cache.getCurriculumNatureValueById(entity.getCurriculumNature());
					if(courseEntity.isMustCount(curriculumNatureValueById)){
						if(entity.getSchoolTerm()==1){
							/**第一学期*/
							tmp.setFirst_item_mainPoint(tmp.getFirst_item_mainPoint()+entity.getCourseCredit().doubleValue());
							tmp.setFirst_item_gradePoint(tmp.getFirst_item_gradePoint()+entity.getCourseGradePoint().doubleValue());
						}else if(entity.getSchoolTerm()==2){
							tmp.setSecond_item_mainPoint(tmp.getSecond_item_mainPoint()+entity.getCourseCredit().doubleValue());
							tmp.setSecond_item_gradePoint(tmp.getSecond_item_gradePoint()+entity.getCourseGradePoint().doubleValue());
						}
					}
				}
			}
			Set<String> keySet = main.keySet();
			ArrayList<ArrayList<SimpleCourseResult>> final_result=new ArrayList<>();
			List<Double> order=new ArrayList<>();
			//先按年份计算
			for(String str:keySet){
				ArrayList<SimpleCourseResult> temp=new ArrayList<>();
				Map<String, SimpleCourseResult> map = main.get(str);
				Set<String> keySet2 = map.keySet();
				//这里包含每个年份的数据
				for(String key:keySet2){
					SimpleCourseResult simpleCourseResult = map.get(key);
					simpleCourseResult.count();
					double avgPoint = simpleCourseResult.getAvgPoint();
					order.add(avgPoint);
					temp.add(simpleCourseResult);
				}
				Map<Double, Integer> sortOrder = ValueUtil.sortOrder(order);
				for(int i=0;i<temp.size();i++){
					SimpleCourseResult simpleCourseResult = temp.get(i);
					simpleCourseResult.setOrder(sortOrder.get(simpleCourseResult.getAvgPoint()));
				}
				final_result.add(temp);
			}
			//TODO 年份只取第一个
			result.put("result", final_result.get(0));
			return result;
		}
		throw new DataNullException("传入数据为空");
		
	}
	@Override
	public Object searchDetailCourse(StudentMessageSearchDto dto) {
		Map<String, Object> result = new HashMap<>();
		if (dto != null && !StringUtils.isEmpty(dto.getFlag())) {
			dto.setOpenPage(false);
			/**
			 * 查询学生基本信息
			 */
			List<BasicDBObject> studentsSno = stuService.getStudentsSno(dto);
			Map<String, BasicDBObject> stuMap = new HashMap<>();
			List<String> snoList = new ArrayList<>();
			/** value->id映射 */
			Map<String, String> idMap = stuMsgMapService.getAllMsgIdMap(dto.getFlag());
			/** 将学号放入数组，方便后面进行数据库查询,另加入映射Map,为后面装载对象做准备 */
			if (studentsSno != null && studentsSno.size() > 0) {
				for (BasicDBObject obj : studentsSno) {
					String sno = obj.getString(idMap.get(STUDENT_MESSAGE_SNO));
					snoList.add(sno);
					stuMap.put(sno, obj);
				}
			}
			/** MYSQL数据库查询 */
			MBG_CourseAchievementExample example = new MBG_CourseAchievementExample();
			Criteria criteria = example.createCriteria();
			criteria.andUserIdLike(ValueUtil.getFlag(dto.getFlag(), PRO_LEVEL) + PER_PATTERN);
			criteria.andStudentIdIn(snoList);
			/** 遍历year数组（可能存在多个year） */
			List<String> year = dto.getAcademic_year();
			List<Byte> yearVals = new ArrayList<>();
			if (year != null) {
				for (String str : year) {
					if (!StringUtils.isEmpty(str)) {
						Integer value = cache.getYearByValue(str);
						yearVals.add((byte) value.intValue());
					}
				}
				criteria.andAcademicYearIn(yearVals);
			}
			/** 遍历可能存在的学期 */
			List<Integer> item = dto.getItem();
			if (item != null) {
				for (Integer i : item) {
					if (i != 1 && i != 2) {
						throw new DataIllegalException("学期参数不合法");
					}
				}
				criteria.andSchoolTermIn(item);
			}
			/** 按学号、学分排下序 */
			example.setOrderByClause(ORDER_CAUSE_SQL);
			if (dto.getPageIndex() != null && dto.getPageSize() != null) {
				/**分页会对下一条SQL起作用，所以只能放在前面*/
				int count = mapper.countByExample(example);
				result.put(RESULT_PAGE_KEY, new DBPageMessage(dto.getPageIndex(), dto.getPageSize(), count));
				Page<?> page = PageHelper.startPage(dto.getPageIndex(), dto.getPageSize(), true);
			}
			/** 查询数据库，并封装对象 */
			List<MBG_CourseAchievement> selectByExample = mapper.selectByExample(example);
			List<CourseDetailEntity> data=new ArrayList<>();
			for (MBG_CourseAchievement entity : selectByExample) {
				String sno = entity.getStudentId();
				BasicDBObject basicDBObject = stuMap.get(sno);
				CourseDetailEntity ent=new CourseDetailEntity();
				ent.setStudentBasicMessageValue(basicDBObject, idMap);
				ent.setMBG_CourseAchievement(entity, cache);
				data.add(ent);
			}
			result.put("result", data);
			return result;
		}
		throw new DataNullException("传入数据为空");
	}

}
